package dao

import (
	"fmt"
	"github.com/fsnotify/fsnotify"
	"github.com/go-redis/redis"
	_ "github.com/go-sql-driver/mysql"
	"github.com/kotlin2018/mbt"
	rotatelogs "github.com/lestrrat-go/file-rotatelogs"
	"github.com/spf13/viper"
	"go.uber.org/zap"
	"go.uber.org/zap/zapcore"
	"io"
	"log"
	"os"
	"path"
	"time"
)

var (
	Cfg         Config
	RedisClient *redis.Client
	Log         *zap.Logger //日志记录器
	level       zapcore.Level
	Vp          *viper.Viper
)

// 全局总配置文件的配置结构体
type Config struct {
	Database *mbt.Database //第一个数据库的配置项
	Zap      *Zap
	Redis    *Redis
}

func init() {
	v := viper.New()
	v.SetConfigFile("./config.toml")
	err := v.ReadInConfig()
	if err != nil {
		log.Fatalln("Fatal error config file :", err.Error())
	}
	v.WatchConfig()
	v.OnConfigChange(func(in fsnotify.Event) {
		log.Println("config file changed:", in.Name)
		if err = v.Unmarshal(&Cfg); err != nil {
			log.Fatalln(err)
		}
	})
	if err = v.Unmarshal(&Cfg); err != nil {
		log.Fatalln(err)
	}
}

// 初始化 database connect
func init() {
	engine := mbt.New(Cfg.Database)
	engine.Register(initMapper())
	engine.SetOutPut(initLogger(Cfg.Database.Logger.Path, Cfg.Database.Logger.MaxAge, Cfg.Database.Logger.Interval))
	engine.Run()
}
func initMapper() map[interface{}]interface{} {
	h := mbt.H{

		&LiAdminUserDao:                   &LiAdminUser{},                   //
		&LiAfterSaleDao:                   &LiAfterSale{},                   //
		&LiAfterSaleLogDao:                &LiAfterSaleLog{},                //
		&LiAfterSaleReasonDao:             &LiAfterSaleReason{},             //
		&LiAppVersionDao:                  &LiAppVersion{},                  //
		&LiArticleDao:                     &LiArticle{},                     //
		&LiArticleCategoryDao:             &LiArticleCategory{},             //
		&LiBillDao:                        &LiBill{},                        //
		&LiBrandDao:                       &LiBrand{},                       //
		&LiCategoryDao:                    &LiCategory{},                    //
		&LiCategoryBrandDao:               &LiCategoryBrand{},               //
		&LiCategoryParameterGroupDao:      &LiCategoryParameterGroup{},      //
		&LiCategorySpecificationDao:       &LiCategorySpecification{},       //
		&LiCommodityDao:                   &LiCommodity{},                   // 直播间商品
		&LiConnectDao:                     &LiConnect{},                     //
		&LiConnectConfigDao:               &LiConnectConfig{},               //
		&LiCouponDao:                      &LiCoupon{},                      //
		&LiCouponActivityDao:              &LiCouponActivity{},              // 优惠券活动
		&LiCouponActivityItemDao:          &LiCouponActivityItem{},          // 优惠券活动-优惠券关联
		&LiCustomWordsDao:                 &LiCustomWords{},                 //
		&LiDepartmentDao:                  &LiDepartment{},                  //
		&LiDepartmentRoleDao:              &LiDepartmentRole{},              //
		&LiDistributionDao:                &LiDistribution{},                //
		&LiDistributionCashDao:            &LiDistributionCash{},            //
		&LiDistributionGoodsDao:           &LiDistributionGoods{},           //
		&LiDistributionOrderDao:           &LiDistributionOrder{},           //
		&LiDistributionSelectedGoodsDao:   &LiDistributionSelectedGoods{},   //
		&LiDraftGoodsDao:                  &LiDraftGoods{},                  //
		&LiFeedbackDao:                    &LiFeedback{},                    //
		&LiFileDao:                        &LiFile{},                        //
		&LiFootPrintDao:                   &LiFootPrint{},                   //
		&LiFreightTemplateDao:             &LiFreightTemplate{},             //
		&LiFreightTemplateChildDao:        &LiFreightTemplateChild{},        //
		&LiFullDiscountDao:                &LiFullDiscount{},                //
		&LiGoodsDao:                       &LiGoods{},                       //
		&LiGoodsCollectionDao:             &LiGoodsCollection{},             //
		&LiGoodsGalleryDao:                &LiGoodsGallery{},                //
		&LiGoodsParamsDao:                 &LiGoodsParams{},                 //
		&LiGoodsSkuDao:                    &LiGoodsSku{},                    //
		&LiGoodsUnitDao:                   &LiGoodsUnit{},                   //
		&LiGoodsWordsDao:                  &LiGoodsWords{},                  //
		&LiInstantDeliveryDao:             &LiInstantDelivery{},             //
		&LiInstantDeliveryLogDao:          &LiInstantDeliveryLog{},          //
		&LiLogisticsDao:                   &LiLogistics{},                   //
		&LiMemberDao:                      &LiMember{},                      //
		&LiMemberAddressDao:               &LiMemberAddress{},               //
		&LiMemberCouponDao:                &LiMemberCoupon{},                //
		&LiMemberEvaluationDao:            &LiMemberEvaluation{},            //
		&LiMemberMessageDao:               &LiMemberMessage{},               //
		&LiMemberNoticeDao:                &LiMemberNotice{},                //
		&LiMemberNoticeLogDao:             &LiMemberNoticeLog{},             //
		&LiMemberNoticeSenterDao:          &LiMemberNoticeSenter{},          //
		&LiMemberPointsHistoryDao:         &LiMemberPointsHistory{},         //
		&LiMemberReceiptDao:               &LiMemberReceipt{},               //
		&LiMemberSignDao:                  &LiMemberSign{},                  //
		&LiMemberStatisticsDataDao:        &LiMemberStatisticsData{},        //
		&LiMemberWalletDao:                &LiMemberWallet{},                //
		&LiMemberWithdrawApplyDao:         &LiMemberWithdrawApply{},         //
		&LiMenuDao:                        &LiMenu{},                        //
		&LiMessageDao:                     &LiMessage{},                     //
		&LiNoticeMessageDao:               &LiNoticeMessage{},               //
		&LiNoticeMessageTemplateDao:       &LiNoticeMessageTemplate{},       //
		&LiOrderDao:                       &LiOrder{},                       //
		&LiOrderComplaintDao:              &LiOrderComplaint{},              //
		&LiOrderComplaintCommunicationDao: &LiOrderComplaintCommunication{}, //
		&LiOrderItemDao:                   &LiOrderItem{},                   //
		&LiOrderLogDao:                    &LiOrderLog{},                    //
		&LiPageDataDao:                    &LiPageData{},                    //
		&LiParametersDao:                  &LiParameters{},                  //
		&LiPaymentLogDao:                  &LiPaymentLog{},                  //
		&LiPintuanDao:                     &LiPintuan{},                     //
		&LiPointsGoodsDao:                 &LiPointsGoods{},                 //
		&LiPointsGoodsCategoryDao:         &LiPointsGoodsCategory{},         //
		&LiPromotionGoodsDao:              &LiPromotionGoods{},              //
		&LiPurchaseOrderDao:               &LiPurchaseOrder{},               //
		&LiPurchaseOrderItemDao:           &LiPurchaseOrderItem{},           //
		&LiPurchaseQuotedDao:              &LiPurchaseQuoted{},              //
		&LiPurchaseQuotedItemDao:          &LiPurchaseQuotedItem{},          //
		&LiReceiptDao:                     &LiReceipt{},                     //
		&LiRechargeDao:                    &LiRecharge{},                    //
		&LiRefundLogDao:                   &LiRefundLog{},                   //
		&LiRegionDao:                      &LiRegion{},                      //
		&LiSPlatformViewDataDao:           &LiSPlatformViewData{},           //
		&LiSeckillDao:                     &LiSeckill{},                     //
		&LiSeckillApplyDao:                &LiSeckillApply{},                //
		&LiSensitiveWordsDao:              &LiSensitiveWords{},              //
		&LiServiceNoticeDao:               &LiServiceNotice{},               //
		&LiSettingDao:                     &LiSetting{},                     //
		&LiShortLinkDao:                   &LiShortLink{},                   //
		&LiSmsReachDao:                    &LiSmsReach{},                    //
		&LiSmsSignDao:                     &LiSmsSign{},                     //
		&LiSmsTemplateDao:                 &LiSmsTemplate{},                 //
		&LiSpecValuesDao:                  &LiSpecValues{},                  //
		&LiSpecialDao:                     &LiSpecial{},                     //
		&LiSpecificationDao:               &LiSpecification{},               //
		&LiStoreDao:                       &LiStore{},                       //
		&LiStoreAddressDao:                &LiStoreAddress{},                //
		&LiStoreCollectionDao:             &LiStoreCollection{},             //
		&LiStoreDetailDao:                 &LiStoreDetail{},                 //
		&LiStoreFlowDao:                   &LiStoreFlow{},                   //
		&LiStoreGoodsLabelDao:             &LiStoreGoodsLabel{},             //
		&LiStoreLogisticsDao:              &LiStoreLogistics{},              //
		&LiStoreMessageDao:                &LiStoreMessage{},                //
		&LiStudioDao:                      &LiStudio{},                      // 直播间
		&LiStudioCommodityDao:             &LiStudioCommodity{},             // 小程序直播-商品关联
		&LiTradeDao:                       &LiTrade{},                       //
		&LiUserRoleDao:                    &LiUserRole{},                    //
		&LiVerificationSourceDao:          &LiVerificationSource{},          //
		&LiWalletLogDao:                   &LiWalletLog{},                   //
		&LiWechatMessageDao:               &LiWechatMessage{},               //
		&LiWechatMpMessageDao:             &LiWechatMpMessage{},             //
		&XxlJobGroupDao:                   &XxlJobGroup{},                   //
		&XxlJobInfoDao:                    &XxlJobInfo{},                    //
		&XxlJobLockDao:                    &XxlJobLock{},                    //
		&XxlJobLogDao:                     &XxlJobLog{},                     //
		&XxlJobLogReportDao:               &XxlJobLogReport{},               //
		&XxlJobLogglueDao:                 &XxlJobLogglue{},                 //
		&XxlJobRegistryDao:                &XxlJobRegistry{},                //
		&XxlJobUserDao:                    &XxlJobUser{},                    //
	}
	return h
}
func initLogger(logFilePath string, maxAge, interval int) io.Writer {
	/* 日志轮转相关函数
	WithLinkName() 	 为最新的日志建立软连接
	WithRotationTime()  设置日志分割的时间，隔多久分割一次
	WithMaxAge() 和 WithRotationCount() 二者只能设置一个
	WithMaxAge()  		 设置文件清理前的最长保存时间
	WithRotationCount() 设置文件清理前最多保存的个数
	*/
	// 下面配置日志每隔 interval 秒轮转一个新文件，保留最近 maxAge 秒的日志文件，多余的自动清理掉。
	writer, _ := rotatelogs.New(
		path.Join(logFilePath+"%Y-%m-%d.log"), //拼接成log文件名
		rotatelogs.WithLinkName(logFilePath),
		rotatelogs.WithMaxAge(time.Duration(maxAge)*time.Hour),
		rotatelogs.WithRotationTime(time.Duration(interval)*time.Hour),
	)
	return writer
}

// 初始化Redis
func init() {
	redisCfg := Cfg.Redis
	client := redis.NewClient(&redis.Options{
		Addr:     redisCfg.Addr,
		Password: redisCfg.Password, // no password set
		DB:       redisCfg.DB,       // use default DB
	})
	pong, err := client.Ping().Result()
	if err != nil {
		Log.Error("redis connect ping failed, err:", zap.Any("err", err))
	} else {
		Log.Info("redis connect ping response:", zap.String("pong", pong))
		RedisClient = client
	}
}

// 初始化Zap日志
func init() {
	// 判断是Director这个变量保存的文件夹是否存在
	if ok := pathExist(Cfg.Zap.Director); ok {
		fmt.Printf("创建 %v 文件夹\n", Cfg.Zap.Director)
		os.Mkdir(Cfg.Zap.Director, os.ModePerm)
	}
	// 初始化配置文件的Level
	switch Cfg.Zap.Level {
	case "debug":
		level = zap.DebugLevel
	case "info":
		level = zap.InfoLevel
	case "warn":
		level = zap.WarnLevel
	case "error":
		level = zap.ErrorLevel
	case "dpanic":
		level = zap.DPanicLevel
	case "panic":
		level = zap.PanicLevel
	case "fatal":
		level = zap.FatalLevel
	default:
		level = zap.InfoLevel
	}
	if level == zap.DebugLevel || level == zap.ErrorLevel {
		Log = zap.New(getEncoderCore(), zap.AddStacktrace(level))
	} else {
		Log = zap.New(getEncoderCore())
	}
	if Cfg.Zap.ShowLine { //显示日志行
		Log = Log.WithOptions(zap.AddCaller())
	}
}

// getEncoderConfig 获取 zapcore的编码器配置
func getEncoderConfig() zapcore.EncoderConfig {
	cfg := zapcore.EncoderConfig{ //定义了输出的样式，比如Key，调用者样式等
		//*Key：设置的是在结构化输出时，value对应的key
		MessageKey:     "message",
		LevelKey:       "level",
		TimeKey:        "time",
		NameKey:        "logger",
		CallerKey:      "caller",
		StacktraceKey:  Cfg.Zap.StacktraceKey,          //堆栈跟踪
		LineEnding:     zapcore.DefaultLineEnding,      //日志的结束符(换行符)
		EncodeLevel:    zapcore.LowercaseLevelEncoder,  //Level的输出样式，比如 大小写，颜色等
		EncodeTime:     CustomLoggerTimeFormat,         //日志时间的输出样式
		EncodeDuration: zapcore.SecondsDurationEncoder, //消耗时间的输出样式
		EncodeCaller:   zapcore.FullCallerEncoder,      //显示完整文件路径 (Caller的输出样式，比如 全名称，短名称)
	}
	switch {
	case Cfg.Zap.EncodeLevel == "LowercaseLevelEncoder": //小写编码器(默认)
		cfg.EncodeLevel = zapcore.LowercaseLevelEncoder
	case Cfg.Zap.EncodeLevel == "LowercaseColorLevelEncoder": //小写编码器带颜色
		cfg.EncodeLevel = zapcore.LowercaseColorLevelEncoder
	case Cfg.Zap.EncodeLevel == "CapitalLevelEncoder": //大写编码器
		cfg.EncodeLevel = zapcore.CapitalLevelEncoder
	case Cfg.Zap.EncodeLevel == "CapitalColorLevelEncoder": //大写编码器带颜色
		cfg.EncodeLevel = zapcore.CapitalColorLevelEncoder
	default:
		cfg.EncodeLevel = zapcore.LowercaseLevelEncoder //默认:小写编码器
	}
	return cfg
}

// getEncoder 获取zapcore.Encoder(日志将以何种格式输出)
// 介绍博客: https://blog.csdn.net/C_jian/article/details/111315457
func getEncoder() zapcore.Encoder {
	if Cfg.Zap.Format == "json" { // https://www.jianshu.com/p/a342a20dc067
		// 将日志以json格式输出到具体的文件中
		return zapcore.NewJSONEncoder(getEncoderConfig()) //使用json编码器输出的日志是json格式,例如:{"level":"info","msg":"this will be logged"}
	}
	return zapcore.NewConsoleEncoder(getEncoderConfig()) //输出普通文本格式
}

// getEncoderCore 获取Encoder的zapcore.Core
// 详情: https://blog.csdn.net/jkwanga/article/details/107186653
func getEncoderCore() (core zapcore.Core) {
	//使用file-rotatelogs进行日志分割 ("github.com/lestrrat-go/file-rotatelogs")
	writer, err := getWriteSyncer()
	if err != nil {
		fmt.Printf("对zap日志文件切割失败:%v", err.Error())
		return
	}
	return zapcore.NewCore(getEncoder(), writer, level)
}

// 自定义日志输出时间格式
func CustomLoggerTimeFormat(t time.Time, enc zapcore.PrimitiveArrayEncoder) {
	enc.AppendString(t.Format(Cfg.Zap.Prefix + "2006/01/02 - 15:04:05.000"))
}

type Zap struct {
	Level         string `json:"level" yaml:"level"`
	Format        string `json:"format" yaml:"format"`
	Prefix        string `json:"prefix" yaml:"prefix"`
	Director      string `json:"director"  yaml:"director"`
	LinkName      string `json:"linkName" yaml:"link-name"`
	ShowLine      bool   `json:"showLine" yaml:"showLine"`
	EncodeLevel   string `json:"encodeLevel" yaml:"encode-level"`
	StacktraceKey string `json:"stacktraceKey" yaml:"stacktrace-key"`
	LogInConsole  bool   `json:"logInConsole" yaml:"log-in-console"`
}

type Redis struct {
	DB       int    `json:"db" yaml:"db"`
	Addr     string `json:"addr" yaml:"addr"`
	Password string `json:"password" yaml:"password"`
}

// 文件目录是否存在
func pathExist(path string) bool {
	_, err := os.Stat(path)
	if err == nil {
		return true
	}
	if os.IsNotExist(err) {
		return false
	}
	return false
}

// zap logger中加入file-rotatelogs ==>切割zap的日志文件
// https://blog.csdn.net/weixin_43881017/article/details/111269642
func getWriteSyncer() (zapcore.WriteSyncer, error) {
	fileWriter, err := rotatelogs.New(
		// 保留7天内的日志,每24小时(整点)分割一次日志
		path.Join(Cfg.Zap.Director, "%Y-%m-%d.log"), //日志文件名,例如:2021-05-04.log , 2021-05-09.log
		rotatelogs.WithLinkName(Cfg.Zap.LinkName),   //创建一个新选项，用于设置链接到当前使用的文件名的符号链接名。
		rotatelogs.WithMaxAge(7*24*time.Hour),
		rotatelogs.WithRotationTime(24*time.Hour),
	)
	if Cfg.Zap.LogInConsole { //日志输出到控制台,日志输出到指定文件
		return zapcore.NewMultiWriteSyncer(zapcore.AddSync(os.Stdout), zapcore.AddSync(fileWriter)), err
	}
	// 日志输出到文件
	return zapcore.AddSync(fileWriter), err
}
